import { Tween } from "./Tween"

export class ShakeScreenHelper {
    private static cameraTweenFunc:Tween<unknown>
    static shake(camera:Camera,force:number,time?:number){
        if(this.cameraTweenFunc && this.cameraTweenFunc.isPlaying()){
            this.cameraTweenFunc.stop()
        }
        let originOffset = camera.springArm.localTransform.position.clone()
        let dir = new mw.Vector(Math.random()*force,Math.random()*force,0)
        let start = camera.springArm.localTransform.position.clone().add(dir)
        let end = camera.springArm.localTransform.position.clone().add(dir.multiply(-1))
        this.cameraTweenFunc = new Tween({x:0})
            .to({x:1},time||200)
            .onUpdate((obj)=>{
                let d = Math.abs(((obj.x + 0.75) % 1) * 2 - 1)
                camera.springArm.localTransform.position = mw.Vector.lerp(start, end, d)
            })
            .onComplete(()=>{
                this.cameraTweenFunc.stop()
            })
            .onStop(()=>{
                camera.springArm.localTransform.position = originOffset
            })
            .start()
    }
}